﻿using WenAntdUI.Services;

namespace WenAntdUI.Controls
{
    [Description("为控件添加权限验证属性")]
    [ProvideProperty("Auth", typeof(AntdUI.Button))]
    public class Auth : Component, IExtenderProvider
    {
        private AdminService adminService;
        public Auth()
        {
            this.adminService = App.GetService<AdminService>();
        }

        public bool CanExtend(object extendee)
        {
            return true;
        }


        private Dictionary<Control, string> controls = new();

        [Description("权限")]
        [DefaultValue(true)]
        public string GetAuth(Control control)
        {
            controls.TryGetValue(control, out var auth);
            return auth;
        }

        public void SetAuth(Control control, string auth)
        {
            if (auth != null) controls[control] = auth;


#if DEBUG
            if (!Helper.IsDesign)
            {
                if (string.IsNullOrEmpty(auth))
                    return;
                if (control is AdminTable adminTable)
                {
                    var s = adminService.AuthorizingPageBlock(auth);
                    adminTable.IsShowAddButton = s.Contains(auth + ":add");
                    adminTable.IsShowEditButton = s.Contains(auth + ":edit");
                    adminTable.IsShowDeleteButton = s.Contains(auth + ":delete");
                }
                else
                {
                    control.Visible = adminService.AuthorizingBlock(auth);
                }
            }
#endif
        }


        [Description("显示")] //虽然方法为Get，但在VS中显示为“设置”才符合理解
        [DefaultValue(true)]
        public bool GetVisible(Control control)
        {
            return control.Visible;
        }

        public void SetVisible(Control control, bool value)
        {
            control.Visible = value;
        }
    }
}
